package com.vids.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.vids.mapper.ImageComparedDetailMapper;
import com.vids.mapper.ImageComparedSummaryMapper;
import com.vids.model.entity.ImageComparedDetail;
import com.vids.model.entity.ImageComparedSummary;
import com.vids.service.IImageComparedService;
import com.vids.utils.ImageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FilenameFilter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.regex.Pattern;

@Slf4j
@Service
public class ImageComparedServiceImpl implements IImageComparedService {

    @Resource
    private  ImageComparedSummaryMapper imageComparedSummaryMapper;

    @Resource
    private  ImageComparedDetailMapper imageComparedDetailMapper;

    public ImageComparedServiceImpl() {

    }

    @Override
    public boolean checkImageIsSame(String viid_image, String ape_image)
    {
        return ImageUtil.isImageContentMD5Same(viid_image,ape_image);
    }

    public static void listFilesRecursively(File dir) {
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    listFilesRecursively(file);
                } else {
                    System.out.println(file.getAbsolutePath());
                }
            }
        }
    }


    public static File[] listFiles(File dir) {
       return dir.listFiles();
    }


    public static void main(String[] args) {

//        String s_viid_dir = "D:\\image\\viid_42022206001320057141";
//        String s_ape_dir = "D:\\image\\ape_42022206001320057141";
//
        String s_viid_dir = "D:/workspace/viid_42022201001320058103_2";
        String s_ape_dir = "D:/workspace/ape_42022201001320058103_2";
//
//
//        log.info("~~~~~~~~~~~~~~~viid_picture~~~~~~~~~~~~~~~");
//        File viid_dir = new File(s_viid_dir); // 替换为你的目录路径
//        listFilesRecursively(viid_dir);
//
//        log.info("~~~~~~~~~~~~~~~picture~~~~~~~~~~~~~~~");
//        File ape_dir = new File(s_ape_dir); // 替换为你的目录路径
//        listFilesRecursively(ape_dir);
//
        new ImageComparedServiceImpl().compareImageNameTimestamp(s_viid_dir, s_ape_dir,
            "42022201001320058103", "11.35.58.103", 14,9);

//        String fileName1= "D:/workspace/ape_42022201001320058103_2/20240526200124_pic_1_faceBackgroundImage.jpg";
//        String fileName2= "D:/workspace/viid_42022201001320058103_2/420222010013200581030220240526200113904120690413.jpg";
//
//        boolean result = ImageUtil.isImageContentMD5Same(fileName1, fileName2);
//
//        if (result)
//        {
//            log.info("The two file are the same.");
//        }else {
//            log.info("The two file are not the same.");
//        }

    }

    public void compareImageNameTimestamp(String viid_dir, String ape_dir, String ape_id,
                                          String ape_ip_addr, int image_type, int compared_hour)
    {
        File f_viid_dir = new  File(viid_dir);
        File[]  viid_files =  f_viid_dir.listFiles();

        File f_ape_dir = new  File(ape_dir);
        File[]  ape_files =  f_ape_dir.listFiles();

        int ape_mount = ape_files.length;
        int viid_mount = viid_files.length;

        log.info("viid_files count=" + viid_mount);
        log.info("ape_files count=" + ape_mount);

        ImageComparedDetail detail = null;
        ImageComparedSummary summary = new ImageComparedSummary();

        int result = -1;
        int matchedCount = 0;

        summary.setApeImageAmount(ape_mount);
        summary.setViidImageAmount(viid_mount);

        if (viid_mount >= ape_mount) {
            for (File vf : viid_files) {
                detail = new ImageComparedDetail();

                detail.setViidImage(vf.getName());

                String dateStr = vf.getName().substring(22, 36);
                detail.setViidImageCreateTime(LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));

                detail.setApeId(ape_id);
                detail.setApeIpAddr(ape_ip_addr);

                result = -1;

                for (File af : ape_files) {

                    result = vf.getName().substring(22, 36).compareTo(af.getName().substring(22, 36));
                    if (result == 0) {
                        matchedCount++;
                        detail.setApeImage(af.getName());
                        detail.setApeImageCreateTime(LocalDateTime.parse(af.getName().substring(22, 36),
                                                                         DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
                        detail.setComparedResult(0);
//                        log.info("file timestamp is " + vf.getName().substring(22, 36));
//                        log.info("Found a matched file for " + vf.getName());
                        log.info("Matched file is " + af.getName());
                        break;
                    }
                }

                if (result != 0) {
                    log.info("Not found matched file for " + vf.getName());
                    detail.setComparedResult(1);
                    detail.setApeImage("");
                }

                detail.setImageType(image_type);
                detail.setComparedHour(compared_hour);
                //将比较结果添加到数据库的详情表中。
                imageComparedDetailMapper.insert(detail);
            }
        }else {
            for (File af : ape_files) {

                detail = new ImageComparedDetail();

                detail.setViidImage(af.getName());
                detail.setApeImageCreateTime(LocalDateTime.parse(af.getName().substring(22, 36),
                                                                 DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));

                detail.setApeId(ape_id);
                detail.setApeIpAddr(ape_ip_addr);

                result = -1;

                for (File vf : viid_files) {
                    result = af.getName().substring(22, 36).compareTo(vf.getName().substring(22, 36));
                    if (result == 0) {
                        matchedCount++;
                        detail.setApeImage(vf.getName());
                        detail.setViidImageCreateTime(LocalDateTime.parse(vf.getName().substring(22, 36),
                                                                          DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
                        detail.setComparedResult(0);
//                        log.info("file timestamp is " + af.getName().substring(22, 36));
//                        log.info("Found a matched file for " + af.getName());
                        log.info("Matched file is " + af.getName());
                        break;
                    }
                }

                if (result != 0) {
                    log.info("Not found matched file for " + af.getName());
                    detail.setComparedResult(1);
                    detail.setApeImage("");
                }

                detail.setImageType(image_type);
                detail.setComparedHour(compared_hour);
                //将比较结果添加到数据库的详情表中。
                detail.setImageType(image_type);
                detail.setComparedHour(compared_hour);
                imageComparedDetailMapper.insert(detail);

            }
        }

        summary.setApeId(ape_id);
        summary.setApeIpAddr(ape_ip_addr);
        summary.setImageType(image_type);
        summary.setMatchedAmount(matchedCount);
        summary.setComparedHour(compared_hour);

        summary.setImageBeginCreateTime(LocalDateTimeUtil.now());
        summary.setImageEndCreateTime(LocalDateTimeUtil.now());

        summary.setImageType(image_type);
        summary.setComparedHour(compared_hour);
        imageComparedSummaryMapper.insert(summary);
    }

    class FileNameFilter1 implements FilenameFilter{
        private Pattern pattern;

        /*传入正则表达式*/
        public FileNameFilter1(String regex) {
            pattern = Pattern.compile(regex);
        }

        @Override
        public boolean accept(File dir, String name) {
            boolean result = pattern.matcher(name).matches();
            return result;
        }
    }

    public void compareImageInDir2(String viid_dir, String ape_dir) {

        File f_viid_dir = new  File(viid_dir);
        FileNameFilter1 filter1 = new FileNameFilter1(".*faceBackgroundImage.*");
        File[]  viid_files =  f_viid_dir.listFiles();

        File f_ape_dir = new  File(ape_dir);
        File[]  ape_files =  f_ape_dir.listFiles(filter1);


        log.info("viid_files count="+viid_files.length);

        log.info("ape_files count="+ape_files.length);

        boolean result = false;

        for(File vf : viid_files)
        {
            result = false;
            log.info("current viid file:" + vf.getName());
            for(File af : ape_files) {
                result = ImageUtil.isImageContentMD5Same(vf, af);
                if (result) {
                    log.info("Have found the same file in ape dir ,the name is "+ af.getName());
                    break;
                }else {
                    log.info("Not found same file as  "+ af.getName());
                }
            }

            if (!result) {
                log.info("Not found the same file for "+ vf.getName());
            }
        }
    }


    /**
     * 按设备ID命名的目录下，按0~23小时命名的目录下的图片，逐个图片进行比对。
     * @param viid_dir  /mount/data1/viid_picture/2024-05-26/20/face/42022201001320058103
     * @param ape_dir   /mount/data1/picture/2024-05-26/20/face/42022201001320058103
     * @return
     */
    @Override
    public boolean compareImageInDir(String viid_dir, String ape_dir) {

        File f_viid_dir = new  File(viid_dir);
        File[]  viid_files =  f_viid_dir.listFiles();

        File f_ape_dir = new  File(ape_dir);
        File[]  ape_files =  f_ape_dir.listFiles();

        boolean result = false;

        for(File vf : viid_files)
        {
            result = false;
            for(File af : ape_files) {
                result = ImageUtil.isImageContentMD5Same(vf, af);
                if (result) {
                    log.info("viid file:" + vf.getName());
                    log.info("ape file:" + af.getName());

                    log.info("find two same file");
                    break;
                }
            }

            if (!result) {
                log.info("viid file:" + vf.getName());
                log.info("Not found the same file as "+ vf.getName());
                break;
            }
        }
        return false;
    }

    @Override
    public void queryComparedResult(Date begin, Date end) {

    }

    @Override
    public void queryComparedResult(int year, int month) {

    }

    @Override
    public void queryComparedResult(Date day, int hour) {

    }

    @Override
    public void queryComparedResult(Date day, int hour, boolean isSame) {

    }
}
